package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**

 * 入住Service业务层处理

 *

 * @author alexis

 * @date 2025-05-27
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;
    /**

     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**

     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**

     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**

     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**

     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**

     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**

     * 入住申请

     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        LambdaQueryWrapper<Elder> elqw =  new LambdaQueryWrapper<>();
        elqw.eq(Elder::getId, checkInApplyDto.getCheckInElderDto().getIdCardNo()).eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elqw);
        if(ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("该老人已入住");
        }

        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        elder=insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(),bed);

        saveContract(checkInApplyDto,elder);

        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto,bed);

        saveCheckInConfig(checkInApplyDto.getCheckInConfigDto(),checkIn);
    }

    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto,  Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        save(checkIn);
        return checkIn;
    }

    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        if(checkInStartTime.isBefore(LocalDateTime.now())){
            contract.setStatus(1);
        }
        String contractNumber ="HT"+ CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> elqw =  new LambdaQueryWrapper<>();
        elqw.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(elqw);
        if(ObjectUtil.isNotEmpty(elderDb)){
            elderMapper.updateById(elder);
        }else{
            elderMapper.insert(elder);
        }
        return elder;
    }
    /**

     * 获取入住详情

     * @param id

     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfigVo checkInInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn, checkInInConfigVo);
        //2.查询老人信息
        Elder elder  = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo elderVo  = new CheckInElderVo();
        BeanUtils.copyProperties(elder, elderVo);
        //3.查询合同
        LambdaQueryWrapper<Contract> contractQuery = new LambdaQueryWrapper<>();
        contractQuery.eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(contractQuery);
        //4.查询入住配置
        LambdaQueryWrapper<CheckInConfig> configQuery = new LambdaQueryWrapper<>();
        configQuery.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(configQuery);
        if (ObjectUtil.isNotEmpty(checkInConfig)) {
            BeanUtils.copyProperties(checkInConfig, checkInInConfigVo);
        }
        // 5.转换家属列表
        String familyJson = checkIn.getRemark(); // 假设家属信息存在 remark 字段
        if (familyJson != null && !familyJson.isEmpty()) {
            List<ElderFamilyDto> elderFamilyDtoList = JSON.parseArray(familyJson, ElderFamilyDto.class);
            List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
            for (ElderFamilyDto dto : elderFamilyDtoList) {
                if (dto == null) {
                    continue; // 跳过 null 元素
                }
                ElderFamilyVo vo = new ElderFamilyVo();
                BeanUtils.copyProperties(dto, vo);
                elderFamilyVoList.add(vo);
            }
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        }

        //6.整合数据返回
        checkInDetailVo.setCheckInConfigVo(checkInInConfigVo);
        checkInDetailVo.setCheckInElderVo(elderVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

}